package com.example.service.user.impl;

import com.example.config.ProjectProperties;
import com.example.dao.CacheDao;
import com.example.exception.InvalidCacheException;
import com.example.exception.InvalidTokenException;
import com.example.pojo.User;
import com.example.service.user.UserAuthenticationService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author LeXin Huang
 * @date 2021年04月27日 20:37
 */
@Service
public class UserAuthenticationServiceImpl implements UserAuthenticationService {

    private final CacheDao cacheDao;

    private final long tokenTimeOut;

    private final TimeUnit tokenTimeUnit;

    public UserAuthenticationServiceImpl(CacheDao cacheDao,
                                         ProjectProperties projectProperties) {
        this.cacheDao = cacheDao;
        this.tokenTimeOut = projectProperties.getToken().getTimeOut();
        this.tokenTimeUnit = projectProperties.getToken().getTimeUnit();
    }

    @Override
    public User login(String token) {
        if (null == token) {
            throw new InvalidTokenException("值为: null 的token不存在!");
        }
        User user = cacheDao.getUserCache(token);
        if (null == user) {
            throw new InvalidTokenException("值为: " + token + " 的token不存在!");
        }
        if (null == user.getUsername()) {
            throw new InvalidCacheException("值为: " + token  + " 的token存储的用户对应的用户名不能为 null");
        }
        cacheDao.set(token, user, this.tokenTimeOut, this.tokenTimeUnit);
        cacheDao.set(user.getUsername(), token, this.tokenTimeOut, this.tokenTimeUnit);
        return user;
    }

}
